<!-- 语言切换组件 -->
<template>
  <div class="language-switcher">
    <button 
      v-for="lang in availableLocales" 
      :key="lang.code"
      :class="{ active: locale === lang.code }"
      @click="changeLanguage(lang.code)"
    >
      {{ lang.name }}
    </button>
  </div>
  
</template>

<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { ElLoading } from 'element-plus'
const { t,locale } = useI18n();
const router = useRouter();

const availableLocales = [//可选择的语言列表
  { code: 'en', name: 'English' },
  { code: 'zh-CN', name: '中文' }
];  

const loading = ref(null)



const changeLanguage = async (lang) => {//切换语言
  if (lang === locale.value) return;

  loading.value = ElLoading.service({
    lock: true,
    text: t('common.loading'),
    background: 'rgba(0, 0, 0, 0.7)',
  })
  
  // 使用非阻塞的延迟
   await delay(1000); //等待3秒,但是不会阻碍主线程渲染,因为使用了非阻塞的延迟
  
  try {
    // 更新i18n语言
    locale.value = lang;

    localStorage.setItem('user-locale', lang);
    
    // 更新URL
    const currentRoute = router.currentRoute.value;
    const redirectPath = `${currentRoute.path}?lang=${lang}`;
    await router.push(redirectPath);
    
  } catch (error) {
    console.error('Failed to change language:', error);
  } finally {
    loading.value.close()
  }
};

const delay = (ms)=>{ //延迟函数
 return new Promise(resolve => setTimeout(resolve, ms));
}

</script>

<style scoped lang="scss">
.language-switcher{
    display: flex;
    gap: 10px;
    button{
        padding: 5px 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        cursor: pointer;
        &.active{
            background-color: #000;
            color: #fff;
        }
    }
}

/**start 切换预言的弹窗 */
.loading-indicator{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    background-color: rgba(199, 37, 37, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 16px;
    font-weight: bold;
}
/**end 切换预言的弹窗 */

.box {
    width: 100px;
    height: 100px;
    background-color: #0d63f8;
    border-radius: 10px;
  }
</style>
